const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const CssMinimizerWebpackPlugin = require('css-minimizer-webpack-plugin')
const toml = require('toml')
const yaml = require('yaml')
const json5 = require('json5')

module.exports = {
  mode: 'development', // 模式 development production
  entry: './src/index.js',
  output: {
    filename: 'bundle.js', // 输出js文件名
    path: path.resolve(__dirname, './dist'), // 借助path模块配置绝对路径
    clean: true, // 打包清理上次的 dist
    // assetModuleFilename: 'images/test.png', // 配置资源打包目录和名称(固定)
    assetModuleFilename: 'images/[contenthash][ext]', // [根据内容生成hash值][扩展名]
  },
  devtool: 'inline-source-map', // 用于锁定代码报错位置
  plugins: [
    new HtmlWebpackPlugin({
      template: './index.html', // 模板文件
      filename: 'app.html', // 输出文件名字
      inject: 'body', // 插入位置 head （默认）和 body
    }),
    new MiniCssExtractPlugin({
      filename: 'styles/[contenthash].css'
    })
  ],
  devServer: {
    static: './dist', // 静态文件索引位置
  },
  module: {
    rules: [{
      test: /\.png$/,
      type: 'asset/resource',
      generator: {
        // filename: 'images/test.png',
        filename: 'images/[contenthash][ext]',
      }
    }, {
      test: /\.svg$/,
      type: 'asset/inline',
    }, {
      test: /\.txt$/,
      type: 'asset/source'
    }, {
      test: /\.jpg$/,
      type: 'asset',
      parser: {
        dataUrlCondition: {
          maxSize: 4 * 1024, // 4kb
          // maxSize: 1 * 1024 * 1024, // 1M
        }
      }
    }, {
      test: /\.(woff|woff2|eot|ttf|otf)$/,
      type: 'asset/resource',
    },
    {
      test: /\.(css|less)$/,
      // 从右向左 先 用css-loader识别css文件打包没有问题，在使用style-loader放置到页面上
      // use: ['style-loader', 'css-loader', 'less-loader'],
      use: [MiniCssExtractPlugin.loader, 'css-loader', 'less-loader'],
    }, {
      test: /\.(csv|tsv)$/,
      use: ['csv-loader'],
    }, {
      test: /\.xml$/,
      use: ['xml-loader'],
    }, {
      test: /\.toml$/,
      type: 'json',
      parser: {
        parse: toml.parse
      }
    }, {
      test: /\.yaml$/,
      type: 'json',
      parser: {
        parse: yaml.parse
      }
    }, {
      test: /\.json5$/,
      type: 'json',
      parser: {
        parse: json5.parse
      }
    }]
  },
  optimization: {
    minimizer: [
      new CssMinimizerWebpackPlugin()
    ]
  }
}